package com.hugy.test.rabbitmq01;

import com.hugy.test.basic.RabitMQConnection;
import com.hugy.test.basic.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 蚂蚁课堂创始人-余胜军QQ644064779
 * @title: Consumer
 * @description: 每特教育独创第五期互联网架构课程
 * @date 2019/12/322:18
 */
public class Consumer2 {


    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println(">>>消费者02启动：" );
        // 1.创建我们的连接
        Connection connection = RabitMQConnection.getConnection();
        // 2.创建我们通道
        final Channel channel = connection.createChannel();
        // MQ每次只会给消费者发送一条消息，必须返回ack之后才会继续发送消息给消费者
        channel.basicQos(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("消费消息msg:" + msg);
                // 手动发送消息告诉给mq服务器端  从队列删除该消息
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        // 3.创建我们的监听的消息 auto Ack 默认自动签收  必须手动ack
        channel.basicConsume(Constants.BASIC_QUEUE_NAME, false , defaultConsumer);

    }
}
